<template>
	<view
		scroll-y="true"
		:class="view"
		class="wrap"
		@tap="onTap"
		@scroll="scrollmore"
		@scrolltoupper="refresh"
		upper-threshold='-50'
		:scroll-into-view="toView" style="padding-bottom: 200rpx;">
		<view class="message" v-for="item in chatMsg" :key="item.mid" :id="item.mid">
			<!-- <view class="time">
				<text class="time-text">{{ item.time }}</text>
			</view> -->
			<template v-if="item.msg.data[0].data == '医生正在为您开电子处方,请稍侯'">
				<view class="main" style="padding: 0rpx;text-align: center;">
					<view style="background: #E7F9F9;font-size: 24rpx;color: #BBBBBB;border-radius: 16px;width: auto;display: inline-block;padding: 10rpx 24rpx;margin-top: 24rpx;">
						医生正在为您开电子处方,请稍侯...
					</view>
				</view>
			</template>
			<template v-else-if="item.msg.data[0].data == '医生已为您开具处方，正由药师审核，请稍候'">
				<view class="main" style="padding: 0rpx;text-align: center;">
					<view style="background: #E7F9F9;font-size: 24rpx;color: #BBBBBB;border-radius: 16px;width: auto;display: inline-block;padding: 10rpx 24rpx;margin-top: 24rpx;">
						医生已为您开具处方，正由药师审核，请稍候...
					</view>
				</view>
			</template>
			<template v-else-if="item.msg.type == 'chufang'">
				<view class="main" style="padding: 0rpx;display: flex;align-items: center;justify-content: center;">
					<view @click="tochufangxq(item.msg.recipe_id)" style="margin-top: 24rpx;background: #F28C87;border-radius: 20rpx;display: flex;align-items: center;justify-content: center;height: 200rpx;padding: 20rpx;">
						<image src="../../../static/images/cfd@2x.png"
							style="margin-right: 40rpx;height:150rpx;" mode="heightFix"/>
						<view style="height:150rpx;display: flex;flex-direction: column;justify-content: space-between;">
							<text style="font-size: 28rpx;color: #FFFFFF;">已为您开具普通药品处方</text>
							<view style="padding: 15rpx 30rpx;display: flex;align-items: center;justify-content: center;
								border: 2rpx solid #FFFFFF;border-radius: 35rpx;">
								<text style="color: #FFFFFF;">诊断和处方详情></text>
							</view>
						</view>
						<!-- <view style="border-radius: 10rpx;">
							<view style="background: #E7F9F9;
								display: flex;align-items: center;justify-content: center;padding:20rpx 20rpx;">
								<image src="../../../static/images/danz@2x.png" 
									style="margin-right: 10rpx;height:32rpx;" mode="heightFix"/>
								<text style="font-size: 32rpx;margin-right: 10rpx;">处方单</text>
								<text style="font-size: 24rpx;color: #BBBBBB;">已为您开具普通药品处方</text>
							</view>
							<view style="padding: 20rpx 20rpx;
								background: #FFFFFF;display: flex;align-items: center;justify-content: center;">
								<text style="color: #2A82E4;">诊断和处方详情></text>
							</view>
						</view> -->
					</view>
				</view>
			</template>
			<view class="main" :class="item.style" v-else>
				<view class="user">
					<!-- yourname：就是消息的 from -->
					<!-- <text class="user-text">{{ item.yourname + ' ' + item.time}}</text> -->
					<text class="user-text">{{item.time}}</text>
				</view>
				<image class="avatar" :src="item.userHead" v-if="item.yourname==username.myName"/>
				<image class="avatar" :src="item.doctorHead" v-else/>
				<template>
					<view class="msg" :style="{
						'background': item.style == 'self'?'#A9ECEC':'#ffffff'
					}">
						<image
						class="err" :class="(item.style == 'self' && item.isFail) ?  'show' : 'hide'"
						src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/msgerr.png"/>
						
						<!-- <image v-if="item.style == 'self'" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/poprightarrow@2x.png" class="msg_poprightarrow"/>
						<image v-if="item.style == ''" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/popleftarrow@2x.png" class="msg_popleftarrow"/> -->
						<view v-if="item.msg.type == 'img' || item.msg.type == 'video'">
							
							
							<image  v-if="item.msg.type == 'img'"
									class="avatar"
									:src="item.msg.data"
									style="width:90px; height:120px; margin:2px auto;"
									mode="aspectFit"
									@tap="previewImage"
									:data-url="item.msg.data" />
							<video v-if="item.msg.type == 'video'" :src="item.msg.data" controls autoplay />
						</view>
						<audio-msg
							v-if="item.msg.type == 'audio'"
							:msg="item"></audio-msg>
						<view v-else-if="item.msg.type == 'txt' || item.msg.type == 'emoji'">
							<!-- <view class="template">
								<text class="msg-text" style="float:left;">{{ JSON.stringify(item.msg.data) }}</text>
							</view> -->
							<view class="template" v-for="(d_item, d_index) in item.msg.data" :key="d_index">
								<text v-if="d_item.type == 'txt'"  class="msg-text" style="float:left;">{{ d_item.data }}</text>
								
								<image  v-if="d_item.type == 'emoji'"
										class="avatar"
										:src="'http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/faces/' + d_item.data"
										style="width:25px; height:25px; margin:0 0 2px 0; float:left;" />
								
							</view>
							
						</view>
						
						
						
						
						
					</view>
					
				</template>
				
				
			</view>
		</view>
		<!-- <view v-if="ischufangxq" style="position: fixed;bottom: 170rpx;z-index: 999;display: flex;align-items: center;width: 100vw;justify-content: center;">
			<view style="background-color: #278fff;color: #FFFFFF;padding: 40rpx;border-radius: 25rpx;" @click="tochufangxq">
				<view>已为患者发送药品处方</view>
				<view style="margin-top: 20rpx;border: 2rpx solid #FFFFFF;padding: 20rpx 10rpx;text-align: center;border-radius: 50rpx;">诊断和处方详情</view>
			</view>
		</view> -->
	</view>
	<!-- <view style="height: 1px;"></view> -->
</template>

<script>
	import audioMsg from "@/comps/chat/msglist/type/audio/audio.vue";
	
	let msgStorage = require("../msgstorage");
	let disp = require("../../../utils/broadcast");
	let LIST_STATUS = {
		SHORT: "scroll_view_change",
		NORMAL: "scroll_view"
	};
	let page = 0;
	let Index = 0;
	let curMsgMid = ''
	let isFail = false
	export default {
		components: {
			audioMsg
		},
		props: {
			username: {
				type: Object,
				value: {},
			},
			orderExt: {
				type: Object,
				value: {},
			},
		},
		data() {
			return {
				shenghetgId: undefined,
				ischufangxq: false,
				chatHistoryMsg: [],//聊天历史记录
				view: LIST_STATUS.NORMAL,
				toView: "",
				chatMsg: [],
				visibility: false,
			}
		},
		beforeMount(){
			this.visibility = true;
			page = 0;
			Index = 0;
		},
		beforeDestroy() {
			this.visibility = false;
		},
		created() {
			//app端虽然会触发created，但是读取local storage为空
			// #ifdef H5
			this.create_or_onready();
			// #endif
		},
		
		onReady() {
			// #ifndef H5
			this.create_or_onready();
			// #endif
		},
		methods: {
			tochufangxq(id){
				uni.navigateTo({
				    url: '/pages3/prescriptiondetail/index?recipeId='+id
				});
			},
			create_or_onready() {
					let me = this;
					let username = this.username;
					let myUsername = uni.getStorageSync("myUsername");
					let sessionKey = username.groupId
						? username.groupId + myUsername
						: username.your + myUsername;
					
					let chatMsg = uni.getStorageSync(sessionKey) || [];
					
					this.renderMsg(null, null, chatMsg, sessionKey);
					uni.setStorageSync(sessionKey, null);
					
					disp.on('em.xmpp.error.sendMsgErr', function(err) {
						curMsgMid = err.data.mid
						isFail = true
						return
					});
					
					disp.on('em.xmpp.error.sendMsgErrOff', function(err) {
						isFail = false
					});
					
					msgStorage.on("newChatMsg",(renderableMsg, type, curChatMsg, sesskey)=>{
						me.curChatMsg = curChatMsg;
						// console.log("curChatMsg curChatMsg",curChatMsg)
						// console.log("curChatMsg renderableMsg",renderableMsg)
						if(!me.visibility) return;
						
						
						// 判断是否属于当前会话
						if(username.groupId){
							// 群消息的 to 是 id，from 是 name
							if(renderableMsg.info.from == username.groupId || renderableMsg.info.to == username.groupId){
								if (sesskey == sessionKey) {
									me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
								}
								
							}
						}
						else if(renderableMsg.info.from == username.your || renderableMsg.info.to == username.your){
							if (sesskey == sessionKey) {
								me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
							}
						}
					
					});
					
			},
			normalScroll(){
				this.view = LIST_STATUS.NORMAL
			},
			
			shortScroll(){
				this.view = LIST_STATUS.SHORT
			},
			
			onTap(){
				// console.log('onTap');
				this.$emit('msglistTap');
				// this.triggerEvent("msglistTap", null, { bubbles: true });
			},
			
			previewImage(event){
				var url = event.target.dataset.url;
				uni.previewImage({
					urls: [url]		// 需要预览的图片 http 链接列表
				});
			},
			
			getHistoryMsg(){
				console.log('getHistoryMsg');
				// return;
				let me = this;
				var history = [];
				let historyChatMsgs = wx.getStorageSync("rendered_") || [];
				if(historyChatMsgs.length>0){
					historyChatMsgs.forEach(function(item,index){
						if(item.orderId ==me.orderExt.orderId){
							history.push(item);
						}
					});
				}			
				if (Index < history.length) {
					let timesMsgList = history.slice(-Index-10, -Index)
					console.log(timesMsgList)		
					me.chatMsg = timesMsgList.concat(me.chatMsg);
					me.toView = timesMsgList[timesMsgList.length - 1].mid;
					// this.setData({
					// 	chatMsg: timesMsgList.concat(me.data.chatMsg),
					// 	toView: timesMsgList[timesMsgList.length - 1].mid,
					// });
					Index += timesMsgList.length;
					if (timesMsgList.length == 10) {
						page ++
					}
					wx.stopPullDownRefresh()
				}
			},
			renderMsg(renderableMsg, type, curChatMsg, sessionKey, isnew){
				 let me = this;
				if (curChatMsg.length > 1) {
					this.chatMsg.map(function(elem, index) {
						curChatMsg.map(function(item, i) {
							if(elem.mid == item.mid){
								//me.data.chatMsg.splice(index, 1)
								curChatMsg.splice(i, 1)
							}
						})
					})
				}
				var historyChatMsgs = uni.getStorageSync("rendered_") || [];
				historyChatMsgs = historyChatMsgs.concat(curChatMsg);
				console.log('历史消息', historyChatMsgs)
				if(curChatMsg.length>0){
					curChatMsg[0].userHead = me.orderExt.userHead;
					curChatMsg[0].doctorHead = me.orderExt.doctorHead;
				}
				if(!historyChatMsgs.length) return;
				var history = [];
				historyChatMsgs.forEach(function(item,index){
					if(item.orderId ==me.orderExt.orderId){
						history.push(item);
					}
				});
				if (isnew == 'newMsg'&&curChatMsg.orderId == me.orderExt.orderId) {
					this.chatMsg = this.chatMsg.concat(curChatMsg)
					this.toView = history[history.length - 1].mid
				}else{
					this.chatMsg = history.slice(-10)
					if(typeof history[history.length - 1] !='undefined'){
						this.toView  = history[history.length - 1].mid
					}else{
						this.toView = 1;
					}
					
				}
				uni.setStorageSync("rendered_", historyChatMsgs);
				
				let chatMsg = uni.getStorageSync(sessionKey) || [];
				chatMsg.map(function(item, index) {
					curChatMsg.map(function(item2, index2) {
						if (item2.mid == item.mid) {
							chatMsg.splice(index, 1)
						}
					})
				})
					
				uni.setStorageSync(sessionKey, chatMsg);
				Index = historyChatMsgs.slice(-10).length;
				uni.pageScrollTo({
					scrollTop: 9999,
				})
			   historyChatMsgs.forEach(item=>{
				   if(item.style != 'self'){
					   var bodyId = item.mid.substring(3)
					   var ackMsg = new this.$im.message("read", this.$im.conn.getUniqueId());
					   ackMsg.set({
					   	id: bodyId,
					   	to: item.yourname
					   });
					   console.log(ackMsg.body)
					   this.$im.conn.send(ackMsg.body);
				   }
			   })
			   // let docMsgs = historyChatMsgs.filter(item=>item.style != 'self')
			   
			   // docMsgs.forEach(item=>)
			   
			   //let lastDocMsgs = docMsgs[docMsgs.length-1]
			   
				uni.request({
					url: 'https://app.mzmzb.com/application-usrapp/wx/settingRead.tz',
					data: {orderId : uni.getStorageSync('chatorderId')},
					method:"GET",
					success: (res) => {
						console.log(res)
					},
					fail(errMsg) {
						console.log(error)
					},
					
				})

				
				
				if (isFail) {
					this.renderFail(sessionKey)
				}
			},
			
			renderFail(sessionKey){
				let me = this
				let msgList = me.chatMsg
				msgList.map((item) =>{
					if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
						item.msg.data[0].isFail = true
						item.isFail = true
						me.chatMsg = msgList
					}
				})
				if (me.curChatMsg[0].mid == curMsgMid) {
					me.curChatMsg[0].msg.data[0].isShow = false;
					me.curChatMsg[0].isShow = false
				}
				uni.setStorageSync("rendered_" + sessionKey, msgList);
				isFail = false
			},
		}
	}
</script>

<style>
	/*.chat-bg{
		position:fixed;
		width: 100%;
		height: 100%;
		z-index: 0;
		top: 50px;
	}*/
	.scroll_view,
	.scroll_view_change {
		/*width: 100%;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 150rpx;*/
		margin-bottom: 174rpx;
		background-color: #FAFAFA;
	}
	
	.scroll_view_X,
	.scroll_view_change_X{
		margin-bottom: 244rpx;
	}
	
	.scroll_view_change {
		/*bottom: 440rpx;*/
		margin-bottom: 590rpx;
	}
	
	.message {
		width: 92%;
		height: auto;
		padding: 0 30rpx;
		position: relative;
	
	}
	
	.time {
		margin: 14rpx 0;
		text-align: center;
	}
	
	.time .time-text {
		display: inline-block;
		padding: 6rpx 20rpx 0 20rpx;
		font-size: 24rpx;
		color: #fff;
		line-height: 28rpx;
		border-radius: 4rpx;
		background-color: #dcdcdc;
	}
	
	.user .user-text {
		margin: auto 100rpx 8rpx;
		font-size: 20rpx;
		color: #dcdcdc;
		display: block;
	}
	
	.avatar {
		width: 72rpx;
		height: 72rpx;
		margin: 0 20rpx 0 0;
		border-radius: 6rpx;
		float: left;
	}
	
	.msg {
		display: inline-block;
		padding: 20rpx;
		max-width: calc(85% - 80rpx);
		min-height: 40rpx; 
		font-size: 24rpx;
		/*overflow: hidden;*/
		text-align: left;
		word-break: break-all;
		background-color: #fff;
		border-radius: 26rpx;
		position: relative;
		margin-top: 24rpx;
	}
	
	.msg .msg_poprightarrow {
		position: absolute;
		right: -10rpx;
		height: 18rpx;
		width: 18rpx;
		margin-top: -10rpx;
	}
	
	.msg .msg_popleftarrow{
		position:absolute;
		left: -14rpx;
		height: 18rpx;
		width: 18rpx;
		margin-top: -10rpx;
	}
	
	.msg .msg-text {
		line-height: 40rpx;
		font-size: 32rpx;
		margin: 0;
	}
	
	/*.msg:before {
		content: " ";
		position: absolute;
		top: 9px;
		right: 100%;
		border: 6px solid transparent;
		border-right-color: #EDEDED;
	}*/
	
	.self {
		text-align: right;
	}
	
	.self .avatar {
		float: right;
		margin: 0 0 0 20rpx;
	}
	
	.user {
		position: relative;
		bottom: -30rpx;
	}
	
	.self .msg {
		background-color: #0873DE;
		color: #fff;
	}
	
	.self .msg:before {
		right: inherit;
		left: 100%;
		border-right-color: transparent;
		border-left-color: #b2e281;
	}
	
	.template {
		display: inline;
	}
	.err{
		width: 32rpx;
		height: 32rpx;
		position: absolute;
		left: -40rpx;
	}
	.hide{
		display: none;
	}
	.show{
		display: block;
	}

</style>
